import React, { Component } from 'react'

import {myAjax, ROOTURL, ROOTPATH} from './../publicAPI/publicAPI'
import style from './login.css'

export default React.createClass({
		getInitialState: function() {
			return {
				username: '',
				password: '',

				errorM: '',
				hasClicked: false
			};
		},
		handleChange: function(e) {
			var newState = {};
			newState[e.target.name] = e.target.value;
			this.setState(newState);
		},
		handleKeyPress: function(e) {
			if(e.which == 13) {
				this.handleSubmit();
			}
		},
		handleSubmit: function() {
			var that = this;
			/*const username = this.refs.username.value,
				  password = this.refs.password.value;*/
			const username = this.state.username,
				  password = this.state.password;
			this.setState({hasClicked: true});
			if(!username || !password) {
				username ? this.refs.password.focus() : this.refs.username.focus();

				this.setState({errorM: "用户名或密码不能为空！", hasClicked: false});
			} else {
				this.setState({errorM: ''});
				const data = {
					login: username,
					pass: password,
					authentication: "SECRET"
				};
				const  newUrl = ROOTURL + 'user/auth/passwd/login.api';

				// 登陆计时30s
				if(this.hasClicked) {
					setTimeout('loginTimeOut()', 30000);
				}

				myAjax(newUrl, "POST", data, function(data) {
					localStorage.setItem("userInfo", JSON.stringify(data))
						if(data.token) {
							location.href = '/'
						}
					}, function(err) {
						this.setState({errorM: "用户名或密码错误！", hasClicked: false});
					}.bind(that)
				);
			}

		},
		loginTimeOut: function() {
			alert("登陆超时，请重新登陆");
			location.reload();// 刷新页面
		},
		render: function() {
			var username = this.state.username;
			var password = this.state.password;
			return (
				<div className={style["loginBox"]} onKeyPress={this.handleKeyPress}>
					<div className={style["login-logo"]}>
						<img src="./../imgs/logo.jpg" alt="logo" />
					</div>
					<form className={style["login-form"]}>
						<div className={style["login-input"]}>
							<label>
								账号：
								<input type="text" name="username" ref="username" value={username} maxLength="20" placeholder="请输入账号" onChange={this.handleChange} />
							</label>
						</div>
						<div className={style["login-input"]}>
							<label>
								密码：
								<input type="password" name="password" ref="password" value={password} maxLength="20" placeholder="请输入密码" onChange={this.handleChange} />
							</label>
						</div>
						<p className={style["login-errorM"]}>{this.state.errorM}</p>
						<div>
							<button type="button" className={style["login-btn"]} onClick={this.handleSubmit} onKeyPress={this.handleKeyPress} disabled={this.state.hasClicked}>
								{this.state.hasClicked ? <span className={style["login-loding"]}></span> : "登陆"}
							</button>
						</div>
					</form>
				</div>
			);
		}
});
